package net.wanho.controller;

import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Author：汤小洋
 * Date：2024-08-16 11:07
 * Description：<描述>
 */
@RestController
@RequiredArgsConstructor
public class LockController {

    private final StringRedisTemplate redisTemplate;
    private final RedissonClient redissonClient;

    @GetMapping("/deductStock")
    public String deductStock() {
        System.out.println(Thread.currentThread().getName() + "线程正在下单。。。。。。。。。");

        // 获取锁（加锁）
        String lockName = "stock_lock";
        RLock rLock = redissonClient.getLock(lockName);
        rLock.lock(); // 默认加锁时间为30秒

        int total = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
        if(total>0){
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            total = total - 1;
            redisTemplate.opsForValue().set("stock",String.valueOf(total));
            // 释放锁
            rLock.unlock();
            return "下单成功，库存还剩：" + total;
        }
        // 释放锁
        rLock.unlock();
        return "下单失败，库存不足";
    }

}
